<template>
  <div class="enterprise-manage">
    <h2 class="page-title">🏢 企业管理</h2>
    
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.name" placeholder="企业名称" clearable />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.status" placeholder="状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="正常" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 添加企业
      </el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table :data="tableData" v-loading="loading" border stripe>
        <el-table-column prop="enterpriseId" label="ID" width="80" />
        <el-table-column prop="enterpriseName" label="企业名称" min-width="180" />
        <el-table-column prop="description" label="企业简介" min-width="200" show-overflow-tooltip />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="pagination.total > 0"
        class="pagination"
        :current-page="pagination.current"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="formData" ref="formRef" label-width="100px">
        <el-form-item label="企业名称" required>
          <el-input v-model="formData.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="企业简介">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入企业简介" />
        </el-form-item>
        <el-form-item label="企业福利">
          <el-input v-model="formData.benefits" type="textarea" :rows="2" placeholder="请输入企业福利" />
        </el-form-item>
        <el-form-item label="评分">
          <el-rate v-model="formData.rating" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)

const searchForm = reactive({
  name: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const formData = reactive({
  enterpriseId: null,
  enterpriseName: '',
  description: '',
  benefits: '',
  rating: 0,
  status: 'active'
})

const dialogTitle = computed(() => formData.enterpriseId ? '编辑企业' : '添加企业')

const loadData = async (page = 1) => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: page.toString(),
      pageSize: pagination.pageSize.toString()
    })
    if (searchForm.name) params.append('name', searchForm.name)
    if (searchForm.status) params.append('status', searchForm.status)
    
    const res = await fetch(`http://localhost:7001/api/enterprises?${params.toString()}`)
    const json = await res.json()
    console.log('企业列表响应:', json)
    if (json.code === 200) {
      console.log('企业数据:', json.data)
      tableData.value = json.data || []
      pagination.total = json.pagination?.total || 0
      pagination.current = page
    } else {
      console.error('企业列表错误:', json)
    }
  } catch (e) {
    console.error('获取企业列表失败:', e)
    ElMessage.error('获取企业列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => loadData(1)
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  loadData(1)
}
const handlePageChange = (page) => loadData(page)

const handleAdd = () => {
  Object.assign(formData, {
    enterpriseId: null,
    enterpriseName: '',
    description: '',
    benefits: '',
    rating: 0,
    status: 'active'
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formData.enterpriseName) {
    ElMessage.warning('请输入企业名称')
    return
  }
  try {
    const url = formData.enterpriseId 
      ? `http://localhost:7001/api/enterprises/${formData.enterpriseId}`
      : 'http://localhost:7001/api/enterprises'
    const method = formData.enterpriseId ? 'PUT' : 'POST'
    
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    })
    const json = await res.json()
    if (json.code === 200 || json.code === 201) {
      ElMessage.success(formData.enterpriseId ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadData(pagination.current)
    } else {
      ElMessage.error(json.message || '操作失败')
    }
  } catch (e) {
    console.error('操作失败:', e)
    ElMessage.error('操作失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该企业吗？', '警告', {
      type: 'warning'
    })
    const res = await fetch(`http://localhost:7001/api/enterprises/${row.enterpriseId}`, {
      method: 'DELETE'
    })
    const json = await res.json()
    if (json.code === 200) {
      ElMessage.success('删除成功')
      loadData(pagination.current)
    } else {
      ElMessage.error(json.message || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除失败:', e)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.enterprise-manage {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card,
.toolbar-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>

